package com.example.dynapermission

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
import com.example.dynapermission.theme.DynaPermissionTheme

class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            DynaPermissionTheme {
                Scaffold { paddingValues ->
//                    PermissionInterceptor(modifier = Modifier.padding(paddingValues),
//                        content = {
//                            Text("Happy with Camera!")
//                        },
//                        noPermission = {
//                            Text("To use this app, you must grant CAMERA permission!")
//                        }
//                    )

                    MultiplePermissionsInterceptor(modifier = Modifier.padding(paddingValues),
                        content = {
                            Text("Happy with Camera!")
                        },
                        noPermission = {
                            Text("To use this app, you must grant CAMERA permission!")
                        }
                    )
                }
            }
        }
    }
}

@Composable
fun PermissionInterceptor(
    modifier: Modifier = Modifier,
    content: @Composable BoxScope.() -> Unit,
    noPermission: @Composable BoxScope.() -> Unit
) {
    val context = LocalContext.current
    val permission = Manifest.permission.CAMERA
//    val permission = Manifest.permission.READ_MEDIA_AUDIO

    var isGranted by remember {
        mutableStateOf<Boolean?>(null)
    }// isGranted 默认为 null

    val permissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission()
    ) { granted ->
        isGranted = granted
    }

    Box(modifier = modifier, contentAlignment = Alignment.Center) {
        if (isGranted == true || ContextCompat.checkSelfPermission(
                context,
                permission
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            content()
        } else if (isGranted == null) {
            LaunchedEffect(key1 = permissionLauncher) {
                permissionLauncher.launch(permission)
            }
        } else {
            noPermission()
        }
    }


}


@Composable
fun MultiplePermissionsInterceptor(
    modifier: Modifier = Modifier,
    content: @Composable BoxScope.() -> Unit,
    noPermission: @Composable BoxScope.() -> Unit
) {
    val context = LocalContext.current
    val permissions = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.ACCESS_COARSE_LOCATION,
        Manifest.permission.ACCESS_FINE_LOCATION,
    )
    var isGranted by remember {
        mutableStateOf<Boolean?>(null)
    }
    val permissionLauncher =
        rememberLauncherForActivityResult(contract = ActivityResultContracts.RequestMultiplePermissions()) { granted ->
            isGranted = granted.all {

                Log.e("TAG", "key= ${it.key} value = ${it.value} ", )
                it.value
            }
        }

    Box(modifier = modifier, contentAlignment = Alignment.Center) {
        if (isGranted == true || permissions.all {
                ContextCompat.checkSelfPermission(
                    context,
                    it
                ) == PackageManager.PERMISSION_GRANTED
            }
        ) {
            content()
        } else if (isGranted == null) {
            LaunchedEffect(key1 = permissionLauncher) {
                permissionLauncher.launch(permissions)
            }
        } else {
            noPermission()
        }
    }
}
